import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(), // 登录以后获取到token口令内容
    name: '', // 获取用户的名称
    avatar: '' // 获取用户的头像
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // 获取用户信息以后再设置名称与头像
  SET_USERINFO(state, userInfo) {
    state.name = userInfo.name
    state.avatar = userInfo.avatar
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 希望是返回的promise
  // async login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   const response = await login({
  //     username: username.trim(),
  //     password: password
  //   })
  //   if (response.code === 20000) {
  //     const { data } = response
  //     commit('SET_TOKEN', data.token)
  //     setToken(data.token) // 是将token信息设置于本地的存储当中，并且明确存储的对象是cookie
  //     return 'ok'
  //   } else {
  //     return new Promise(new Error('fail'))
  //   }
  // },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response

          if (!data) {
            return reject('Verification failed, please Login again.')
          }

          // const { name, avatar } = data
          // commit('SET_NAME', name)
          // commit('SET_AVATAR', avatar)
          commit('SET_USERINFO', data) // 将name与avatar进行userInfo的统一处理
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
